/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package org.dromara.setting.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.setting.domain.SettingConfigGroup;
import org.dromara.setting.domain.SettingConfigItem;
import org.dromara.setting.domain.bo.SettingConfigGroupBo;
import org.dromara.setting.domain.vo.SettingConfigGroupVo;
import org.dromara.setting.domain.vo.SettingConfigItemVo;
import org.dromara.setting.enums.SettingAllEnums.AliPayEnums;
import org.dromara.setting.enums.SettingAllEnums.BalancePayEnums;
import org.dromara.setting.enums.SettingAllEnums.WxPayEnums;
import org.dromara.setting.mapper.SettingConfigGroupMapper;
import org.dromara.setting.mapper.SettingConfigItemMapper;
import org.dromara.setting.service.ISettingConfigGroupService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配置组Service业务层处理
 *
 * @author LXK-RY5
 * @date 2024-08-10
 */
@RequiredArgsConstructor
@Service
public class SettingConfigGroupServiceImpl implements ISettingConfigGroupService {

    private final SettingConfigGroupMapper baseMapper;
    private final SettingConfigItemMapper settingConfigItemMapper;


    /**
     * 查询Type
     */
//    @Cacheable(cacheNames = "SettingConfig:cache#60s", key = "#type", condition = "#type != null")
    @Override
    public SettingConfigGroupVo queryByType(String type) {
        return baseMapper.selectVoOne(Wrappers.<SettingConfigGroup>lambdaQuery().eq(SettingConfigGroup::getType, type));
    }

    @Override
    public List<SettingConfigGroupVo> queryListByType(String type) {
        return baseMapper.selectVoList(Wrappers.<SettingConfigGroup>lambdaQuery().eq(SettingConfigGroup::getType, type));
    }

    /**
     * 查询IdList配置组Map
     */
    @Override
    public Map<Long, SettingConfigGroupVo> queryMapByIdList(List<Long> idList) {
        return this.queryByIdList(idList).stream().collect(Collectors.toMap(SettingConfigGroupVo::getId, v -> v));
    }

    /**
     * 查询配置组Map
     */
    @Override
    public Map<Long, SettingConfigGroupVo> queryMap(SettingConfigGroupBo bo) {
        return this.queryList(bo).stream().collect(Collectors.toMap(SettingConfigGroupVo::getId, v -> v));
    }

    /**
     * 查询配置组IdList
     */
    @Override
    public List<SettingConfigGroupVo> queryByIdList(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<SettingConfigGroup> lqw = Wrappers.lambdaQuery();
        lqw.in(SettingConfigGroup::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询配置组
     *
     * @param id 主键
     * @return 配置组
     */
    @Override
    public SettingConfigGroupVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询配置组列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 配置组分页列表
     */
    @Override
    public TableDataInfo<SettingConfigGroupVo> queryPageList(SettingConfigGroupBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SettingConfigGroup> lqw = buildQueryWrapper(bo);
        Page<SettingConfigGroupVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的配置组列表
     *
     * @param bo 查询条件
     * @return 配置组列表
     */
    @Override
    public List<SettingConfigGroupVo> queryList(SettingConfigGroupBo bo) {
        LambdaQueryWrapper<SettingConfigGroup> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SettingConfigGroup> buildQueryWrapper(SettingConfigGroupBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SettingConfigGroup> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(SettingConfigGroup::getId);
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            SettingConfigGroup::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            SettingConfigGroup::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getName()), SettingConfigGroup::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SettingConfigGroup::getType, bo.getType());
        lqw.eq(bo.getSortNum() != null, SettingConfigGroup::getSortNum, bo.getSortNum());
        return lqw;
    }

    /**
     * 新增配置组
     *
     * @param bo 配置组
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SettingConfigGroupBo bo) {
        SettingConfigGroup add = MapstructUtils.convert(bo, SettingConfigGroup.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改配置组
     *
     * @param bo 配置组
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SettingConfigGroupBo bo) {
        SettingConfigGroup update = MapstructUtils.convert(bo, SettingConfigGroup.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SettingConfigGroup entity) {
    }

    /**
     * 校验并批量删除配置组信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<SettingConfigGroupVo> queryPayList() {
        List<SettingConfigGroupVo> list = baseMapper.selectVoList(Wrappers.<SettingConfigGroup>lambdaQuery().in(SettingConfigGroup::getType, BalancePayEnums.YUE, AliPayEnums.ALL_PAY, WxPayEnums.WX_PAY));
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        List<Long> idList = list.stream().map(SettingConfigGroupVo::getId).collect(Collectors.toList());
        List<String> keys = CollUtil.newArrayList(BalancePayEnums.ICON.getKey(), BalancePayEnums.SORT.getKey(), BalancePayEnums.STATE.getKey());

        LambdaQueryWrapper<SettingConfigItem> lqw = new LambdaQueryWrapper<>();
        lqw.in(CollUtil.isNotEmpty(idList), SettingConfigItem::getConfigGroupId, idList);
        lqw.in(CollUtil.isNotEmpty(keys), SettingConfigItem::getKey, keys);
        List<SettingConfigItemVo> itemVos = settingConfigItemMapper.selectVoList(lqw);
        Map<Long, Map<String, String>> map = new HashMap<>();
        if (CollUtil.isNotEmpty(itemVos)) {
            map = itemVos.stream().collect(Collectors.groupingBy(SettingConfigItemVo::getConfigGroupId, Collectors.toMap(SettingConfigItemVo::getKey, SettingConfigItemVo::getValue)));
        }
        Map<Long, Map<String, String>> finalMap = map;
        list.forEach(e -> {
            Map<String, String> itemMap = finalMap.get(e.getId());
            if (CollUtil.isNotEmpty(itemMap)) {
                if (StrUtil.isNotBlank(itemMap.get(BalancePayEnums.ICON.getKey()))) {
                    e.setImage(itemMap.get(BalancePayEnums.ICON.getKey()));
                }
                String sort = itemMap.get(BalancePayEnums.SORT.getKey());
                if (StrUtil.isNotBlank(sort) && NumberUtil.isNumber(sort)) {
                    e.setSort(Integer.valueOf(sort));
                }
                String state = itemMap.get(BalancePayEnums.STATE.getKey());
                if (StrUtil.isNotBlank(state)) {
                    e.setState(!state.equals(BigDecimal.ZERO.toString()));
                }
            }
        });
        return list;
    }
}
